<template>
  <div class="map">
    <div ref="mapBox" class="mapBox">
      <div id="mapContiner" class="mapContiner" ref="mapContiner"></div>
    </div>
    <div class="right-box">
      <div class="group">
        <div class="type-title">底图切换</div>
        <el-radio-group v-model="ditu_radio" @change="changeDitu()">
          <el-radio-button label="1">天地图</el-radio-button>
          <el-radio-button label="2">ArcGIS影像</el-radio-button>
          <el-radio-button label="3">蓝色底图</el-radio-button>
          <el-radio-button label="4">星图电子</el-radio-button>
        </el-radio-group>
      </div>
      <div class="group">
        <div class="type-title">控件显示</div>
        <el-checkbox-group v-model="control_checkbox" @change="changeControl()">
          <el-checkbox-button label="1">鹰眼地图</el-checkbox-button>
        </el-checkbox-group>
      </div>
      <div class="group">
        <div class="type-title">黑夜变天效果</div>
        <span>时间进度条,当前时间 {{ time }}</span>
        <el-slider v-model="slider_time" :step="1" :max="1440" @input="changeTime(val)"></el-slider>
      </div>
      <div class="group">
        <div class="type-title">二三维地图联动(双屏对比)</div>
        <el-checkbox-button @click="changeMapType()">开启地图对比</el-checkbox-button>
      </div>
      <div class="group">
        <div class="type-title">地图下钻（深圳）</div>
        <el-button-group class="btnGroup">
          <el-button @click="goTosz()">返回深圳视角</el-button>
          <el-button @click="goBack()">返回之前视角</el-button>
        </el-button-group>
        <el-button-group class="btnGroup">
          <el-button @click="add_szMaskLayer()">深圳视角显示遮罩</el-button>
          <!-- <el-button @click="addMaskGraphic()">深圳视角显示遮罩矢量</el-button> -->
          <el-button @click="removeMask()">深圳视角取消遮罩</el-button>
        </el-button-group>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, onUnmounted } from 'vue'
import * as turf from '@turf/turf'
import * as mars3d from 'mars3d'
import { deepClone } from '@/utils/utils'
import * as szSs from '@/assets/json/szSs.json' //json数据可以直接使用，而geojson则需要放入public文件并发起请求
import * as szQu from '@/assets/json/qu.json'
import * as szJd from '@/assets/json/sz_jd.json'
import * as szSq from '@/assets/json/sz_sq.json'
import { regionShijiao, regionShijiao_2D } from '@/assets/config/shijiao_config.js'
const mapContiner = ref()
const ditu_radio = ref('1')
const control_checkbox = ref(['1'])
const slider_time = ref(0)
const time = ref()
const mapSplit = ref() //地图分裂
const mapSplit_map = ref()
const mapBox = ref()
let map = ref()
let overallMap = {}
let clickObj_toRemoveBorder = {
  quName: null,
  jdName: null
}
let Cesium = mars3d.Cesium
const mapOptions = {
  scene: {
    center: { lat: 33.596051, lng: 119.031383, alt: 359, heading: 180, pitch: -43 },
    fxaa: true,
    globe: {
      baseColor: '#000'
    }
  },
  // control: {
  //   baseLayerPicker: true
  // },
  basemaps: [
    {
      id: 1,
      name: '天地图影像',
      icon: 'img/basemaps/tdt_img.png',
      type: 'tdt',
      layer: 'img_d',
      show: true
    },
    {
      id: 2,
      name: 'ArcGIS影像',
      icon: 'img/basemaps/esriWorldImagery.png',
      type: 'arcgis',
      layer: 'img_d', // 使用layer时会自动用内部固定url "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
      enablePickFeatures: false,
      show: false
    },
    {
      id: 3,
      name: '蓝色底图',
      icon: 'img/basemaps/bd-c-midnight.png',
      type: 'arcgis',
      url: 'http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer',
      enablePickFeatures: false,
      chinaCRS: mars3d.ChinaCRS.GCJ02,
      show: false
    },
    {
      id: 4,
      name: '星图电子',
      icon: '/img/basemaps/tdt_vec.png',
      type: 'xyz',
      url: 'https://tiles{s}.geovisearth.com/base/v1/vec/{z}/{x}/{y}?token=82455ef06c72bb3a35bbb4d7d05fd9eceb96a94dc942a056b8feb0e5928ed96f',
      subdomains: '123'
    }
  ],
  layers: [],
  control: {
    // overviewMap: true
    compass: { parentContainer: mapContiner.value, bottom: '10px' }
  }
  // globe: {
  //   showGroundAtmosphere: true,
  //   enableLighting: true
  // }
}
const symbol_styleOptions = {
  //默认是根据数据生成 point、polyline、polygon
  fill: true, //设置为填充，鼠标事件范围就为填充区域
  randomColor: true, // 随机色
  opacity: 0.01,
  outline: false, //区域边界
  outlineStyle: {
    color: '#FED976',
    width: 3,
    opacity: 1
  },
  // 高亮时的样式
  highlight: {
    opacity: 0.9,
    outlineStyle: {
      width: 6,
      color: '#ff0000',
      addHeight: 100
    },
    label: { show: true }
  }
}
//构造鹰眼地图
const overviewMap = new mars3d.control.OverviewMap({
  basemap: {
    name: '天地图电子',
    type: 'group',
    layers: [
      { name: '底图', type: 'tdt', layer: 'vec_d' },
      { name: '注记', type: 'tdt', layer: 'vec_z' }
    ]
  },
  rectangle: {
    color: '#fecd78',
    opacity: 0.2,
    outline: 1,
    outlineColor: '#ff7800'
  },
  style: {
    left: '0px',
    bottom: '-150px',
    width: '200px',
    height: '150px'
  }
})
// 构造时钟
// const clock = new mars3d.control.ClockAnimate({})
// 添加模型图层并添加模型
const tilesetLayer = new mars3d.layer.TilesetLayer({
  url: '//data.mars3d.cn/3dtiles/qx-simiao/tileset.json',
  position: { alt: 38.8 },
  maximumScreenSpaceError: 1,
  shadows: Cesium.ShadowMode.ENABLED //确定tileset是否投射或接收来自光源的阴影。
})
// 添加阴影
const shadows = new mars3d.thing.Shadows({
  darkness: 0.4, //阴影透明度
  multiplier: 1700, //时钟倍率，控制速度
  // time:Date   //当前时间
  terrain: true, //是否投射到地形
  lighting: true
})
onMounted(() => {
  map.value = new mars3d.Map('mapContiner', mapOptions)
  let imageryLayer = map.value.scene.imageryLayers.get(0)
  imageryLayer.dayAlpha = 1.0 //白天图层透明值
  imageryLayer.nightAlpha = 0.1 //夜晚图层透明值
  overviewMap.addTo(map.value)
  // clock.addTo(map.value)
  map.value.addLayer(tilesetLayer)
  map.value.addThing(shadows)
  addQuName()
})
/**
 * @param {*} val
 * @returns 底图切换
 */
const changeDitu = val => {
  map.value.basemap = ditu_radio.value
}
/**
 * @returns 控件显示隐藏
 */
const changeControl = val => {
  overviewMap.show = !overviewMap.show
}
/**
 * @returns 更改地图时间，添加黑夜变天
 */
const changeTime = val => {
  const hours = Math.floor(slider_time.value / 60) // 根据滑块的值计算小时和分钟
  const minutes = slider_time.value % 60
  time.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}` // 格式化时间字符串
  const currentDate = new Date() // 如果需要Date对象，可以这样获取
  currentDate.setHours(hours, minutes, 0, 0) // 设置小时、分钟、秒和毫秒
  shadows.time = currentDate
  console.log('Current date-time:', currentDate)
}
const timeInit = val => {
  const time = new Date()
  const hours = time.getHours()
  const minutes = time.getMinutes()
  slider_time.value = hours * 60 + minutes
  console.log(time, 'time')
}
timeInit()
/**
 * @returns 地图二三维联动
 */
const changeMapType = val => {
  if (!mapSplit.value || mapSplit.value.show == false) {
    if (mapSplit.value) {
      const mapOld = mapContiner.value
      mapOld.style.width = mapOld.clientWidth / 2 + 'px'
      mapSplit.value.show = true
      return
    }
    const mapOld = mapContiner.value
    mapOld.style.width = mapOld.clientWidth / 2 + 'px' // 将之前的地图大小变为原来一半
    // const mapOptions2 = map.value.toJSON()//使用不了toJSON可以使用getCurrentOptions()
    const mapOptions2 = deepClone(map.value.getCurrentOptions()) // 获取原来的地图参数
    // const mapOptions2 = mapOptions
    mapOptions2.layers = [] //清空图层（不添加模型）
    mapOptions2.scene.sceneMode = Cesium.SceneMode.SCENE2D
    mapOptions2.control.compass.enabled = false
    console.log(mapOptions2, 'mapOptions2')
    mapSplit.value = new mars3d.control.MapCompare({
      ...mapOptions2,
      parentContainer: mapBox.value, //控件加入的父容器对象
      className: 'mapSplit'
    })
    console.log(mapSplit.value.parentContainer, 'mapSplit.value.parentContainer >>>>>>>>')
    map.value.addControl(mapSplit.value)
    console.log(mapSplit.value.mapEx, 'mapSplit.value.mapEx>>>>>>>>')
    mapSplit_map.value = mapSplit.value.mapEx //mapEx：对比的地图对象即mapSplit，只有当该控件加入到地图实例后才能使用
    mapSplit_map.value.basemap = '星图电子'
    // mapSplit_map.value.scene.morphTo2D()
  } else {
    const mapOld = mapContiner.value
    mapOld.style.width = mapOld.clientWidth * 2 + 'px'
    mapSplit.value.show = false
  }
}

const goBack = val => {
  removeMask()
  map.value.centerAt({ lat: 33.596051, lng: 119.031383, alt: 359, heading: 180, pitch: -43 })
}
const goTosz = val => {
  map.value.hasLayer(maskLayer) ? removeMask(true) : removeMask()
  if (!map.value.hasLayer(quName_GeojsonLayer)) {
    addQuName()
  }
  for (let key in clickObj_toRemoveBorder) {
    //删除街道、社区边界
    removeBorder(clickObj_toRemoveBorder[key])
  }
  map.value.removeLayer(jdName_GeojsonLayer)
  map.value.removeLayer(sqName_GeojsonLayer)
  map.value.camera.flyTo({
    // destination: Cesium.Rectangle.fromDegrees(113.531, 22.935, 114.713, 22.352), // 二维
    destination: Cesium.Cartesian3.fromDegrees(114.16085, 22.629879, 117553), // 二维，相机在 WGS84（世界）坐标中的最终位置或从自上而下视图可见的矩形。
    // 二维
    orientation: {
      heading: Cesium.Math.toRadians(0.0),
      pitch: Cesium.Math.toRadians(-90.0),
      roll: 0.0
    },
    // destination: Cesium.Cartesian3.fromDegrees(114.270257, 21.904684, 59731.1), // 三维
    // orientation: {
    //   heading: Cesium.Math.toRadians(357.0),
    //   pitch: Cesium.Math.toRadians(-35.8),
    //   roll: 0.0
    // },
    duration: 3 //飞行持续时间（秒）
  })
}

/**
 * @param szMask 是否保存深圳遮罩
 * @returns 移除遮罩层
 */
const removeMask = szMask => {
  // if (maskLayer) {
  //   map.value.removeLayer(maskLayer)
  //   // maskLayer.show = false
  //   maskLayer.mask = false
  // }
  const maskList = map.value.getLayersByAttr(true, 'mask') //根据指定属性获取图层列表
  if (maskList.length) {
    maskList.forEach(item => {
      if (szMask && item.options.name === '深圳市GeoJson反遮罩图层') {
        //如果显示深圳遮罩并且该遮罩存在则不清除
        return
      } else {
        map.value.removeLayer(item)
      }
    })
  }
}
/**
 * @returns 创建边界线
 */
const createBorder = (promise, name) => {
  const viewer = map.value
  overallMap.mapBorder = new Cesium.CustomDataSource(name ? name : 'defaultBorder') //创建一个存放实体实例的对象
  // viewer.dataSources.add(overallMap.mapBorder)
  promise.then(res => {
    const entities = res.entities.values
    entities.forEach(item => {
      item.polygon.fill = false
      let positions = item.polygon.hierarchy._value.positions
      item.polygon = { positions: positions }
      item.polyline = {
        show: true,
        positions: positions,
        width: 2.5,
        material: Cesium.Color.fromCssColorString('#E4F3FF'),
        // material: Cesium.Color.fromCssColorString('rgba(0,106,255,0.4)'),
        clampToGround: true
      }
      overallMap.mapBorder.entities.add(item)
    })
    viewer.dataSources.add(overallMap.mapBorder)
  })
}
/**
 * @param name 边界线的实体名称
 * @returns 移除边界线
 */
const removeBorder = name => {
  console.log(name, 'naem:::::::::::::')
  let target
  //边界线是new Cesium.CustomDataSource创建存放在datasources数组中
  for (let i = 0; i < map.value.dataSources._dataSources.length; i++) {
    if (map.value.dataSources._dataSources[i]._name === name) {
      target = i
    }
  }
  const target_dataSources = map.value.dataSources._dataSources[target]
  map.value.dataSources.remove(target_dataSources)
  const jdIndex = jdHistory.findIndex(el => el === name)
  if (jdIndex !== -1) {
    jdHistory.splice(jdIndex, 1)
  }
  const sqIndex = sqHistory.findIndex(el => el === name)
  if (sqIndex !== -1) {
    sqHistory.splice(sqIndex, 1)
  }
}

/**
 * @returns 对深圳区JSON数据进行修改
 */
let quData = {}
const getQuData = () => {
  const { features } = szQu
  for (let i = 0; i < features.length; i++) {
    const el = features[i]
    const { geometry, properties } = el

    const center = turf.center(geometry)
    if (!quData[properties.QNAME]) {
      quData[properties.QNAME] = []
    }
    quData[properties.QNAME].push({
      center,
      ...properties,
      geometry
    })
  }
  console.log(quData, 'quData>>>>>>>>>>>>>>>>>>')
}
getQuData()
/**
 * @returns 对深圳街道JSON数据进行修改
 */
let jdData = {}
const getJdData = () => {
  console.log(szJd, 'szjd>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
  const { features } = szJd
  for (let i = 0; i < features.length; i++) {
    const el = features[i]
    const { geometry, properties } = el
    let jd_name = properties.jd_name
    let qu_name = properties.qu_name
    const center = turf.center(geometry)
    if (!jdData[qu_name]) {
      jdData[qu_name] = []
    }
    jdData[qu_name].push({
      center,
      // jd_name,
      // qu_name,
      properties,
      geometry
    })
  }
  console.log(jdData, 'jdData>>>>>>>>>>>>>>>>>>')
}
getJdData()
/**
 * @returns 对深圳社区JSON数据进行修改
 */
let sqData = {}
const getSqData = () => {
  console.log(szSq, 'szSq>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
  const { features } = szSq
  for (let i = 0; i < features.length; i++) {
    const el = features[i]
    const { properties, geometry } = el
    const center = getCenter(geometry)
    let jd_name = properties.jd_name
    let qu_name = properties.qu_name
    let sq_name = properties.sq_name
    if (!sqData[jd_name]) {
      sqData[jd_name] = []
    }
    sqData[jd_name].push({
      center,
      properties,
      geometry
    })
  }
  console.log(sqData, 'sqData>>>>>>>>>')
}
/**
 *
 * @description 获取中心点坐标
 */
const getCenter = geometry => {
  let feture = turf.center(geometry)
  return feture.geometry.coordinates
}
getSqData()

/**
 * 获取边界
 * @param coordinates 坐标
 * @param type 类型
 * @param buffer 是否缓冲
 * @param radius 缓冲半径
 * @param units 缓冲半径单位，默认kilometers
 * @returns {*}
 */
const getBbox = ({ coordinates, type, buffer, radius = 5, units = 'kilometers' }) => {
  let feature = null
  switch (type) {
    case 'polyline':
      feature = turf.lineString(coordinates)
      break
    case 'multiPolygon':
      feature = turf.multiPolygon(coordinates)
      break
    default:
      feature = turf.polygon(coordinates)
      break
  }
  if (buffer) {
    feature = turf.buffer(feature, radius, {
      units: units
    })
  }
  return turf.bbox(feature)
}
/**
 *定位到范围
 * @param coordinates
 * @param options
 */
const locateBbox = (
  coordinates,
  type = 'MultiPolygon',
  options = {
    scale: 1,
    duration: 1,
    pitch: -90,
    // heading: 7.2,
    // pitch: -29,
    roll: 0.0
  }
) => {
  let bbox = getBbox({
    coordinates: coordinates,
    type: 'multiPolygon',
    buffer: true,
    radius: 6
  })
  let [xmin, ymin, xmax, ymax] = bbox
  map.value.flyToExtent({ xmin, ymin, xmax, ymax }, options)
}
/**
 * @returns 定位到范围
 */
const locatCenter = (options = {}) => {
  map.value.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(options.lng, options.lat, options.alt), // 三维
    orientation: {
      heading: Cesium.Math.toRadians(options.heading),
      pitch: Cesium.Math.toRadians(options.pitch)
    }
  })
}
//<-------------------------------深圳市-区--------------------------------->
/**
 * @returns 添加深圳各区名称GeoJson图层
 */
let quName_GeojsonLayer
const addQuName = () => {
  quName_GeojsonLayer = new mars3d.layer.GeoJsonLayer({
    name: '深圳市区名GeoJson图层',
    url: '/json/qu.geojson',
    symbol: {
      styleOptions: {
        ...symbol_styleOptions,
        label: {
          show: true,
          // 面中心点，显示文字的配置
          text: '{QNAME}', // 对应的属性名称
          opacity: 1,
          font_size: 22,
          color: '#ffffff',
          font_family: '楷体',
          outline: true,
          outlineColor: '#000000',
          outlineWidth: 3,
          background: false,
          backgroundColor: '#000000',
          backgroundOpacity: 0.1,
          font_weight: 'normal',
          font_style: 'normal',
          scaleByDistance: true,
          scaleByDistance_far: 20000000,
          scaleByDistance_farValue: 0.1,
          scaleByDistance_near: 1000,
          scaleByDistance_nearValue: 1,
          distanceDisplayCondition: false,
          distanceDisplayCondition_far: 10000,
          distanceDisplayCondition_near: 0,
          visibleDepth: false
        }
      }
    }
  })
  map.value.addLayer(quName_GeojsonLayer)
  let locatCenter_History = [] //保存跳转位置，防止多次点击多次触发
  quName_GeojsonLayer.on(mars3d.EventType.click, val => {
    const target_Name = val.graphic.options.attr['QNAME']
    addJdBorder(target_Name)
    if (!locatCenter_History.includes(target_Name)) {
      removeBorder(locatCenter_History[0])
      locatCenter(regionShijiao_2D[target_Name])
      locatCenter_History[0] = target_Name
    }
    addQuMask(target_Name)
    addJdName(target_Name)
  })
  addQuBorder()
}
/**
 * @returns 添加深圳市遮罩层
 */
let maskLayer
const add_szMaskLayer = val => {
  //使用GeoJsonLayer生成遮罩层
  maskLayer = new mars3d.layer.GeoJsonLayer({
    name: '深圳市GeoJson反遮罩图层',
    url: '/json/sz.geojson',
    mask: true, // 标识为遮罩层【重点参数】
    format: obj => {
      let data = obj.features
      let szssArr = []
      let szssFeature
      for (let i = 0; i < data.length; i++) {
        const el = data[i]
        szssArr.push(...el.geometry.coordinates)
      }
      console.log(obj, 'masl>>>>>>>>>>>>>>>>>>>>')
      console.log(szssArr, 'szssFeature>>>>>>>>>>>>>>>>>>>>')
      szssFeature = {
        type: 'FeatureCollection',
        name: 'sz',
        features: [
          {
            type: 'Feature',
            geometry: {
              type: 'MultiPolygon',
              coordinates: szssArr
            },
            properties: {
              id: 'shenzhen_shenshan',
              qu_name: '深圳-深汕边界'
            }
          }
        ]
      }
      return szssFeature
    },
    symbol: {
      styleOptions: {
        fill: true,
        color: 'rgb(2,26,79)',
        opacity: 1,
        outline: false,
        outlineColor: '#39E09B',
        outlineWidth: 8,
        outlineOpacity: 0.8,
        arcType: Cesium.ArcType.GEODESIC,
        clampToGround: true
      }
    }
    // flyTo: true
  })
  map.value.addLayer(maskLayer)
}
/**
 * @returns 加载深圳行政区边界线
 */
const addQuBorder = val => {
  //使用本地的json、geojson文件需要放到public目录下,因为Cesium在Web环境中运行时，资源通常从服务器提供。
  const xzqBoundPromise = Cesium.GeoJsonDataSource.load('/json/qu.geojson', {
    stroke: Cesium.Color.TRANSPARENT, //获取或设置多段线和多边形轮廓的默认颜色。
    clampToGround: true //获取或设置是否夹紧到地面的默认值。
  })
  createBorder(xzqBoundPromise)
}

//<-------------------------------深圳市-区-街道--------------------------------->
/**
 * @returns 添加深圳对应区街道边界线
 */
let jdHistory = [] //记录已添加边界线的地区，防止重复添加渲染
const addJdBorder = name => {
  if (jdHistory.includes(name)) {
    return
  }
  jdHistory.push(name)
  let targetJd_Data = jdData[name]
  targetJd_Data.forEach(el => {
    el.type = 'Feature'
  })
  const targetJd_dataSources = {
    type: 'FeatureCollection',
    features: targetJd_Data
  }
  console.log(targetJd_dataSources, 'targetJd_dataSources>>>>>>>>>>>>>>>>>>')
  const jdBoundPromise = Cesium.GeoJsonDataSource.load(targetJd_dataSources, {
    stroke: Cesium.Color.TRANSPARENT, //获取或设置多段线和多边形轮廓的默认颜色。
    clampToGround: true //获取或设置是否夹紧到地面的默认值。
  })
  createBorder(jdBoundPromise, name)
}
/**
 * @returns 指定地区添加遮罩
 */
const addQuMask = val => {
  clickObj_toRemoveBorder.quName = val
  map.value.removeLayer(quName_GeojsonLayer) //地图下钻，显示遮罩层，移除区名图层
  let targetQu_Data = quData[val]
  targetQu_Data.forEach(el => {
    el.type = 'Feature'
  })
  const targetQu_dataSources = {
    type: 'FeatureCollection',
    features: targetQu_Data
  }
  const targetmaskLayer = new mars3d.layer.GeoJsonLayer({
    name: '指定地区GeoJson遮罩图层',

    data: targetQu_dataSources,
    mask: true, // 标识为遮罩层【重点参数】
    symbol: {
      styleOptions: {
        fill: true,
        color: 'rgb(2,26,79)',
        opacity: 1,
        outline: false,
        outlineColor: '#39E09B',
        outlineWidth: 8,
        outlineOpacity: 0.8,
        arcType: Cesium.ArcType.GEODESIC,
        clampToGround: true
      }
    }
    // flyTo: true
  })
  map.value.addLayer(targetmaskLayer)
}
/**
 * @returns 指定地区添加街道名称与'点击事件'（GeoJson）
 */
let jdName_GeojsonLayer
const addJdName = val => {
  let targetJd_Data = jdData[val]
  targetJd_Data.forEach(el => {
    el.type = 'Feature'
  })
  const targetJd_dataSources = {
    type: 'FeatureCollection',
    features: targetJd_Data
  }
  jdName_GeojsonLayer = new mars3d.layer.GeoJsonLayer({
    name: '区街道名GeoJson图层',
    data: targetJd_dataSources,
    symbol: {
      styleOptions: {
        ...symbol_styleOptions,
        label: {
          show: true,
          // 面中心点，显示文字的配置
          text: '{jd_name}', // 对应的属性名称
          opacity: 1,
          font_size: 22,
          color: '#ffffff',
          font_family: '楷体',
          outline: true,
          outlineColor: '#000000',
          outlineWidth: 3,
          background: false,
          backgroundColor: '#000000',
          backgroundOpacity: 0.1,
          font_weight: 'normal',
          font_style: 'normal',
          scaleByDistance: true,
          scaleByDistance_far: 20000000,
          scaleByDistance_farValue: 0.1,
          scaleByDistance_near: 1000,
          scaleByDistance_nearValue: 1,
          distanceDisplayCondition: false,
          distanceDisplayCondition_far: 10000,
          distanceDisplayCondition_near: 0,
          visibleDepth: false
        }
      }
    }
  })
  map.value.addLayer(jdName_GeojsonLayer)
  jdName_GeojsonLayer.on(mars3d.EventType.click, val => {
    const target_Name = val.propagatedFrom.attr.jd_name
    const { attr, positions } = val.graphic.options //获取指定街道的边界坐标数据（存于sz_jd.json中）
    const { qu_name, jd_name } = attr
    let index //获取指定街道在jdData中的位置
    jdData[qu_name].forEach((item, _index) => {
      if (item.properties.jd_name === jd_name) {
        index = _index
      }
    })
    const feature = jdData[qu_name][index]
    addJdMask([feature])
    addSqBorder(target_Name)
    addSqName(target_Name)
    locateBbox([[positions]])
  })
}

//<-------------------------------深圳市-区-街道-社区--------------------------------->
/**
 * @returns 指定街道添加遮罩层
 */
const addJdMask = val => {
  map.value.removeLayer(jdName_GeojsonLayer)
  const targetJd_data = val
  targetJd_data.forEach(el => {
    el.type = 'Feature'
  })
  const targetJd_dataSources = {
    type: 'FeatureCollection',
    features: targetJd_data
  }
  const targetmaskLayer = new mars3d.layer.GeoJsonLayer({
    name: '指定街道GeoJson遮罩图层',
    data: targetJd_dataSources,
    mask: true, // 标识为遮罩层【重点参数】
    symbol: {
      styleOptions: {
        fill: true,
        color: 'rgb(2,26,79)',
        opacity: 1,
        outline: false,
        outlineColor: '#39E09B',
        outlineWidth: 8,
        outlineOpacity: 0.8,
        arcType: Cesium.ArcType.GEODESIC,
        clampToGround: true
      }
    }
    // flyTo: true
  })
  map.value.addLayer(targetmaskLayer)
}
/**
 * @returns 指定社区添加边界线
 */
let sqHistory = [] //记录已添加边界线的街道，防止重复添加渲染
const addSqBorder = name => {
  clickObj_toRemoveBorder.jdName = name

  if (sqHistory.includes(name)) {
    return
  }
  sqHistory.push(name)
  let targetSq_data = sqData[name]
  targetSq_data.forEach(item => {
    item.type = 'Feature'
  })
  const targetSq_dataSources = {
    type: 'FeatureCollection',
    features: targetSq_data
  }
  const jdBoundPromise = Cesium.GeoJsonDataSource.load(targetSq_dataSources, {
    stroke: Cesium.Color.TRANSPARENT, //获取或设置多段线和多边形轮廓的默认颜色。
    clampToGround: true //获取或设置是否夹紧到地面的默认值。
  })
  createBorder(jdBoundPromise, name)
}
/**
 * @returns 指定街道添加社区名称（GeoJson）
 */
let sqName_GeojsonLayer
const addSqName = val => {
  let targetSq_data = sqData[val]
  targetSq_data.forEach(item => {
    item.type = 'Feature'
  })
  const targetSq_dataSources = {
    type: 'FeatureCollection',
    features: targetSq_data
  }
  sqName_GeojsonLayer = new mars3d.layer.GeoJsonLayer({
    name: '社区名称',
    data: targetSq_dataSources,
    symbol: {
      styleOptions: {
        ...symbol_styleOptions,
        label: {
          show: true,
          // 面中心点，显示文字的配置
          text: '{sq_name}', // Json数据中对应properties里面的数据
          opacity: 1,
          font_size: 22,
          color: '#ffffff',
          font_family: '楷体',
          outline: true,
          outlineColor: '#000000',
          outlineWidth: 3,
          background: false,
          backgroundColor: '#000000',
          backgroundOpacity: 0.1,
          font_weight: 'normal',
          font_style: 'normal',
          scaleByDistance: true,
          scaleByDistance_far: 20000000,
          scaleByDistance_farValue: 0.1,
          scaleByDistance_near: 1000,
          scaleByDistance_nearValue: 1,
          distanceDisplayCondition: false,
          distanceDisplayCondition_far: 10000,
          distanceDisplayCondition_near: 0,
          visibleDepth: false
        }
      }
    }
  })
  map.value.addLayer(sqName_GeojsonLayer)
}

const addMaskGraphic = val => {
  let positionArr = []
  console.log(szSs, 'szSs<<<<<<<<<<<<<<<<<<<<<<<<')
  let data = szSs.features //使用深圳-深汕合作区JSON数据
  for (let i; i < data.length; i++) {
    positionArr.push(...data[i].geometry.coordinates)
  }
  const maskGraphicLayer = new mars3d.layer.GraphicLayer()
  map.value.addLayer(maskGraphicLayer)
  const maskGraphic = new mars3d.graphic.Mask({
    position: positionArr,
    style: {
      fill: true,
      color: 'rgb(2,26,79)',
      opacity: 0.9,
      outline: true,
      outlineColor: '#39E09B',
      outlineWidth: 8,
      outlineOpacity: 0.8,
      arcType: Cesium.ArcType.GEODESIC,
      clampToGround: true
    }
  })
  maskGraphicLayer.addGraphic(maskGraphic)
}
</script>
<style>
.mapSplit {
  position: relative;
  width: 50%;
  height: 100%;
}
.map {
  display: flex;
  justify-content: center;
}
.type-title {
  margin-bottom: 6px;
}
.group {
  margin-bottom: 13px;
}
/* .mapContiner {
  margin-right: 20px;
  width: 1200px;
  height: 600px;
} */
.mapBox {
  position: relative;
  display: flex;
  margin-right: 20px;
  width: 1200px;
  height: 600px;
}
.right-box {
  width: 500px;
  display: flex;
  flex-direction: column;
}
.btnGroup {
  margin-bottom: 5px;
}
</style>
